package com.example.util;

import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileUploadUtil {

    public static String upload(MultipartFile file, String path) throws Exception{
        if(file==null){
            throw new Exception("file is null");
        }
        if(path==null){
            throw new Exception("file path is null");
        }
        //获取文件的后缀名
        String fileName = file.getOriginalFilename();
        String suffix = UUID.randomUUID()+fileName.substring(fileName.lastIndexOf("."));
        String filePath = path+"/"+suffix;
        File f = new File(path,suffix);
        if(!f.getParentFile().exists()){
            f.getParentFile().mkdirs();
            f.createNewFile();
        }
        FileUtils.copyInputStreamToFile(file.getInputStream(),f);
        return filePath;
    }

    /**
     * 获得指定文件的byte数组
     */

    public static byte[] getBytes(String filePath) throws Exception{
        byte[] buffer = null;
        File file = new File(filePath);
        FileInputStream fis = new FileInputStream(file);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
        byte[] b = new byte[1000];
        int n;
        while ((n = fis.read(b)) != -1) {
            bos.write(b, 0, n);
        }
        if(fis!=null){
            fis.close();
        }
        if(bos!=null){
            bos.close();
        }
        buffer = bos.toByteArray();
        return buffer;
    }

    /**
      文件压缩
     */
    public static void zipFiles(List<File> srcfile, java.io.File zipfile) {
        byte[] buf=new byte[1024];
        ZipOutputStream out=null;
        try {
            out=new ZipOutputStream(new FileOutputStream(
                    zipfile));
            for (int i=0; i < srcfile.size(); i++) {
                FileInputStream in=new FileInputStream(srcfile.get(i));
                out.putNextEntry(new ZipEntry(srcfile.get(i).getName()));
                int len;
                while ((len=in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                out.closeEntry();
                in.close();
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
